package com.woniuxy.shiro;

import com.woniuxy.dao.ShiroDao;
import com.woniuxy.entity.User;
import com.woniuxy.utils.JWTUtil;
//import com.xzr.Service.ManagerLoginService;
import com.woniuxy.utils.JWTUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Set;

/**
 * @Author：jojo
 * @Date：2022/2/23 17:11
 * @Description :TODO
 */
@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired(required = false)
//    ManagerLoginService managerLoginService;
    ShiroDao shiroDao;
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String token = principals.getPrimaryPrincipal()+"";
        String username = JWTUtil.getUsername(token);
        //去数据库查询该用户所有的角色和权限
//        Set<String> roles = managerLoginService.findAllRoles(username);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//        simpleAuthorizationInfo.setRoles(roles);
        //获取权限
//        Set<String> perms = managerLoginService.findAllPerms(username);
//        simpleAuthorizationInfo.setStringPermissions(perms);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        MyJsonWebToken myJsonWebToken = (MyJsonWebToken) authenticationToken;
        //这里是我们前端传来的token
        String token = myJsonWebToken.getCredentials()+"";
//        String username = JWTUtil.getUsername(token);
        User o = (User) redisTemplate.opsForValue().get(token);
        if (o !=null) {
            return new SimpleAuthenticationInfo(token,token,"MyRealm");
        }else {
            throw new AuthenticationException("token异常，请重新登录");
        }
//        String password = managerLoginService.findPassword(username);
        //校验token是否正常  password是用来做盐的  使加密更加散列
//        boolean verify = JWTUtil.verify(token,username,password);
//        if (verify){
//            return new SimpleAuthenticationInfo(token,token,"myRealm");
//        }else{
//            throw new AuthenticationException("token被修改，请重新登录");
//        }
    }
}
